package com.shiikong_memory.yez.Arknights;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.shiikong_memory.yez.KOOKBasics.Broadcast;
import com.shiikong_memory.yez.MySQLAPI.DaoImpl.SklandServer;
import com.shiikong_memory.yez.MySQLAPI.JavaBean.SklandBean;
import love.forte.simbot.application.Application;
import love.forte.simbot.bot.BotManager;
import love.forte.simbot.bot.BotManagers;
import love.forte.simbot.common.id.Identifies;
import love.forte.simbot.component.kook.bot.KookBot;
import love.forte.simbot.component.kook.bot.KookBotManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
public class AutoCheck_In {
    @Autowired
    private Application application;

    @Autowired
    private SklandAPI sklandAPI;

    @Autowired
    SklandServer sklandServer;

    @Autowired
    Broadcast broadcast;

    /**
     * 定时森空岛签到功能
     */
    @Async
    @Scheduled(cron="0 0 5 * * ?")
    public void stratAutoCheckIn(){
        List<SklandBean> all = sklandServer.getAll();
        int allSize = all.size();
        int Size=0;
        for (SklandBean sklandBean:all){
            String token = sklandBean.getArknightsToken();
            if (!sklandAPI.verifyToken(token)){
                notice(sklandBean.getBotId(), sklandBean.getKookId());
            }else {
                try {
                    String code = sklandAPI.getCode(token);
                    if (code == null) {
                        System.err.println(sklandBean.getKookName() + "无法获取code，请联系管理者进行修复");
                    }
                    JSONObject cred = sklandAPI.getCred(code);
                    if (cred == null) {
                        System.err.println(sklandBean.getKookName() + "无法获取cred，请联系管理者进行修复");
                    }
                    JSONObject jsonObject = sklandAPI.get_binding_list(cred.getString("cred"), cred.getString("token"));
                    if (jsonObject == null) {
                        System.err.println(sklandBean.getKookName() + "无法获取游戏角色，请确定游戏角色已创建");
                    }
                    JSONArray gameList = jsonObject.getJSONObject("data").getJSONArray("list");
                    for (int j=0;j<gameList.size();j++){
                        if ("arknights".equals(gameList.getJSONObject(j).getString("appCode"))){
                            JSONArray bingingList = gameList.getJSONObject(j).getJSONArray("bindingList");
                            for (int i=0;i<bingingList.size();i++){
                                JSONObject jsonObject1 = bingingList.getJSONObject(i);
                                boolean b = sklandAPI.sign_in(cred.getString("cred"), cred.getString("token"), jsonObject1.getString("uid"));
                                if (b){
                                    System.err.println(jsonObject1.getString("channelName")+"森空岛自动签到成功");
                                }else {
                                    System.err.println(jsonObject1.getString("channelName")+"森空岛自动签到失败,可能已签到或鹰角通行证token已失效");
                                }
                            }
                        }
                    }
                    Size++;
                } catch (Exception e) {
                    System.err.println(token + "签到失败");
                }
            }
        }
        broadcast.senndAllMessage(10, Json.formatted(allSize, Size));
        System.out.println("自动签到全部完成（共：%d,成功签到：%s）".formatted(allSize,Size));
    }

    /**
     * 森空岛签到失败：鹰角通行证过期提醒
     * @param botId 机器人ID
     * @param uid KOOK用户ID
     */
    private void notice(String botId, String uid){
        BotManagers botManagers = application.getBotManagers();
        for (BotManager manager : botManagers) {
            // 寻找你所需要的botManager，例如MiraiBotManager
            if (manager instanceof KookBotManager kookBotManager) {
                KookBot bot = (KookBot) kookBotManager.get(Identifies.of(botId));
                bot.getContactRelation().getContact(Identifies.of(uid)).sendAsync("你的鹰角通行证已过期，请重新登录");
            }
        }
    }

    private static String Json = """
            [
              {
                "type": "card",
                "size": "lg",
                "theme": "warning",
                "modules": [
                  {
                    "type": "header",
                    "text": {
                      "type": "plain-text",
                      "content": "森空岛自动签到提醒"
                    }
                  },
                  {
                    "type": "divider"
                  },
                  {
                    "type": "section",
                    "mode": "left",
                    "accessory": {
                      "type": "image",
                      "src": "https://img.kaiheila.cn/assets/2021-01/FckX3MDe6S02i020.png",
                      "circle": true
                    },
                    "text": {
                      "type": "plain-text",
                      "content": "自动签到全部完成（共：%d,成功签到：%s）"
                    }
                  }
                ]
              }
            ]""";
}
